package com.example.control;

import com.example.domain.t_article;
import com.example.domain.t_comment;
import com.example.domain.t_user;
import com.example.service.IArticleService;
import com.example.service.ICommentService;
import com.example.service.ISiteService;
import com.example.service.IUserService;
import com.example.utils.myUtils;

import com.github.pagehelper.PageInfo;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;

import java.io.IOException;
import java.util.*;


@Controller
public class indexController {


    private static final Logger logger = LoggerFactory.getLogger(indexController.class);

    @Value("${file.upload}")
    private String path;

    @Autowired
    private IArticleService art;

    @Autowired
    private ISiteService site;
    @Autowired
    private ICommentService comm;
    @Autowired
    private IUserService iuse;

    //博客首页
    @RequestMapping({"/","/page"})
    public String index(HttpServletRequest req){
        return this.index(req,1, myUtils.pageSize,"",false);
    }



    @RequestMapping("/page/{count}")
    public String index(HttpServletRequest req,
       @PathVariable int count, @RequestParam(defaultValue = "5") int size,
       @RequestParam(defaultValue = "") String like,@RequestParam(defaultValue = "false") boolean only){
        //文章排行


        List<t_article> articleSort =null;
        articleSort=art.selectListSort(count, size);
        req.setAttribute("articleList",articleSort);
        //交给PageInfo自动文章分页
        PageInfo<t_article> res_art = null;

        //只看我的
        t_user loginUser = (t_user)req.getSession().getAttribute("loginUser");
        res_art = art.clientGetPage(like,count,size,loginUser,only);
        logger.info((loginUser!=null?loginUser.getUsername():req.getRemoteAddr())+" 分页查询: "+like+" 的信息：页码："+count+",条数："+Math.min(size,10));


        req.setAttribute("articles",res_art);
        req.setAttribute("likeString",like);
        req.setAttribute("only",only);
        //System.out.println(t_articles);
        //System.out.println(res_art);
        //System.out.println(like);
        return "client/index";
    }
    //文章中图片
    @RequestMapping("/article/image/{id}/{filename}")
    public void getArticleImage(@PathVariable Integer id,@PathVariable String filename,
                                HttpServletResponse response){
        File file = new File(System.getProperty("user.dir") + path + id + "/" + filename);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageInputStream image = new FileImageInputStream(file);
            BufferedImage read = ImageIO.read(image);
            ImageIO.write(read,"jpg",outputStream);
        } catch (IOException e) {
            logger.error("文章 "+id+" 详情图片获取失败，信息："+e.getMessage());
        }

    }

    //文章详情
    @GetMapping("/article/{id}")
    public String getArticleById(@PathVariable int id,HttpServletRequest req){
        //System.out.println("getArticleById:id="+id);
        t_article article = art.selectById(Integer.valueOf(id));
        t_user loginUser = (t_user)req.getSession().getAttribute("loginUser");
        boolean flag=false;


        if(article!=null){

            //是否为可删除文章
            if(loginUser!=null) {
                if(iuse.Isroot(loginUser.getId()))flag = true;
                if(loginUser.getId()==article.getUser_id())flag=true;

            }
            if((!flag) && article.isSecret()){
                logger.warn("用户"+(loginUser!=null?loginUser.getUsername():req.getRemoteAddr())+"越权访问文章:id="+id);
                return "comm/error_404";
            }

            //封装评论相关数据
            getArticleComments(req,article);

            //更新文章点击量
            site.updateStatistic(article);
            //封装数据
            req.setAttribute("article",article);
            req.setAttribute("isDele",flag);
            //System.out.println("sucess");
            return "client/articleDetails";
        }
        logger.warn("未找到该文章:id="+id);
        return "comm/error_404";
    }

    //封装评论
    private void getArticleComments(HttpServletRequest req, t_article article) {
        if(article.getAllow_comment()!=0){
            //cp表示评论的页码
            String cp = req.getParameter("cp");
            cp = StringUtils.isBlank(cp) ? "1" : cp;
            req.setAttribute("cp",cp);
            PageInfo<t_comment> commentlist = comm.getAll(article.getId(), Integer.parseInt(cp), myUtils.pageSize);
            req.setAttribute("comments",commentlist);
        }
    }
    //获取评论者头像
    @RequestMapping("/article/avatar/{author}")
    public void getAvatarById(@PathVariable  String author,HttpServletResponse response){
        String avatar = iuse.getAvatar(author);
        if(avatar==null){
            return ;
        }
        try {
            BufferedImage bufferedImage = myUtils.base64StringToImage(avatar);
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
        } catch (IOException e) {
            logger.error("用户获取头像失败，错误信息："+e.getMessage());
        }
    }

}
